<?php
/**
 * Desc: Service模板
 * User: zdb
 * Date: 2023/6/5
 * Time: 11:22
 */

namespace app\api\service\clockin;
use app\util\DateUtil;
use think\facade\Db;

class ClockinActivityPlanTaskService
{

    private $primaryTable;

    public function __construct()
    {
        $this->primaryTable = "yj_clockin_activity_plan_task";
    }

    public function findRowById($id)
    {
        return Db::table($this->primaryTable)->alias('a')
            ->where('id', '=', $id)
            ->strict(false)
            ->find();
    }

    public function findRowByData($data)
    {
        $condition = $this->assembleFilterCondition($data);
        return Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->strict(false)
            ->find();
    }

    public function getListByManyId($arrId)
    {
        $list = Db::table($this->primaryTable)->alias('a')
            ->whereIn('id', $arrId)
            ->select()
            ->toArray();
        return $list;
    }

    public function assembleFilterCondition($data)
    {
        if(isset($data['status'])){
            if(is_array($data['status'])){
                $condition = ['a.status '.$data['status'][0].$data['status'][1]];
            }else{
                $condition = ['a.status = '.$data['status']];
            }
        }else{
            $condition = array();
        }

        if (!empty($data['title'])) {
            $condition[] = "title like '%" . $data['title'] . "%'";
        }

        if(!empty($data['clockin_activity_id'])){
            $condition[] = "a.clockin_activity_id = ".$data['clockin_activity_id'];
        }

        if(!empty($data['plan_id'])){
            $condition[] = "a.plan_id = ".$data['plan_id'];
        }

        if(!empty($data['plan_month'])){
            $condition[] = "a.plan_date like '".$data['plan_month']."%'";
        }

        if(!empty($data['subject_id'])){
            $condition[] = "a.subject_id = ".$data['subject_id'];
        }

        if(!empty($data['arr_subject_id'])){
            $condition[] = "a.subject_id in (".implode(",", $data['arr_subject_id']).")";
        }

        if(!empty($data['plan_date'])){
            $condition[] = "a.plan_date = '".$data['plan_date']."'";
        }

        return empty($condition) ? "" : implode(" AND ", $condition);
    }

    public function getListNoPage($data = [])
    {
        $list = array();
        switch($data['content_type']){
            case ClockinActivityService::ARR_CONTENT_TYPE['movie_word_en']:
                $data['status'] = array('>', 0);
                $list = $this->getMovieWordPlanListNoPage($data);
                break;
            case ClockinActivityService::ARR_CONTENT_TYPE['poem']:
                $data['status'] = array('>', 0);
                $list = $this->getPoemPlanListNoPage($data);
                break;
            default:
                break;
        }
        return $list;
    }

    public function getSimpleListNoPage($data = [])
    {
        $condition = $this->assembleFilterCondition($data);
        $list = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->select()
            ->toArray();
        return $list;
    }

    public function getMovieWordPlanListNoPage($data = [])
    {
        $condition = $this->assembleFilterCondition($data);
        $list = Db::table($this->primaryTable)->alias('a')
            ->leftJoin("yj_lib_movie_word b", "b.id = a.subject_id")
            ->where($condition)
            ->field("a.*, b.spelling")
            ->select()
            ->toArray();
        return $list;
    }

    public function getPoemPlanListNoPage($data = [])
    {
        $condition = $this->assembleFilterCondition($data);
        $list = Db::table($this->primaryTable)->alias('a')
            ->leftJoin("yj_lib_poem p", "p.id = a.subject_id")
            ->where($condition)
            ->field("a.*, p.poem_title")
            ->select()
            ->toArray();
        return $list;
    }

    public function getListWithPage($data, $pageIndex = 1, $pageSize = 30)
    {
        switch($data['content_type']){
            case ClockinActivityService::ARR_CONTENT_TYPE['poem']:
                $list = $this->getPoemListWithPage($data, $pageIndex, $pageSize);
                break;
            default:
                break;
        }
        return $list;
    }

    public function getTotalNum($data)
    {
        $condition = $this->assembleFilterCondition($data);
        $num = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->count();
        return $num;
    }

    public function getPoemListWithPage($data, $pageIndex = 1, $pageSize = 30){
        $offset = ($pageIndex - 1) * $pageSize;
        $condition = $this->assembleFilterCondition($data);
        $list = Db::table($this->primaryTable)->alias('a')
            ->leftJoin('yj_lib_poem p', 'p.id = a.subject_id')
            ->where($condition)
            ->limit($offset, $pageSize)
            ->order('a.plan_date desc')
            ->field("a.*, p.title, p.poet, p.dynasty, p.content")
            ->select();
        foreach($list as &$item){
            $item['title'] = "<strong>".$item['title']."</strong><span class='poet'>".$item['dynasty']."·".$item['poet']."</span>";
        }
        return $list;
    }

    public function createRow($data)
    {
        $data['status'] = isset($data['status']) ? $data['status']:1;
        $res = Db::table($this->primaryTable)
            ->duplicate(array('subject_id', 'plan_id', 'status'))
            ->strict(false)
            ->insert($data, true);
        return $res;
    }

    public function createManyRow($data)
    {
        $res = Db::table($this->primaryTable)
            ->strict(false)
            ->duplicate(array('clockin_activity_id', 'content_type', 'plan_date', 'subject_id'))
            ->insertAll($data, true);
        return $res;
    }

    public function updateRowById($id, $data)
    {
        $res = Db::table($this->primaryTable)->alias('a')
            ->where('id', '=', $id)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function updateListByData($condition, $data)
    {
        $condition = $this->assembleFilterCondition($data);
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function updateListByManyId($arrId, $data)
    {
        $res = Db::table($this->primaryTable)->alias('a')
            ->whereIn('a.id', $arrId)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeRowById($id)
    {
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)
            ->where('id', '=', $id)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeListByManyId($arrId)
    {
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)->alias('a')
            ->whereIn('a.id', $arrId)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeListByData($data)
    {
        $condition = $this->assembleFilterCondition($data);
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function getListByMonth($clockinActivityId, $month)
    {
        $data = [
            'plan_month' => $month,
            'clockin_activity_id' => $clockinActivityId
        ];
        $condition = $this->assembleFilterCondition($data);
        $list = Db::table($this->primaryTable)->alias('a')
            ->leftJoin("yj_lib_poem b", "b.id = a.subject_id")
            ->where($condition)
            ->field("a.*, b.title,b.dynasty,b.poet")
            ->select()
            ->toArray();
        foreach($list as &$item){
            $w = DateUtil::getCustomDatetime($item['plan_date'], "w");
            $item['is_holiday'] = 0 == $w || 6 == $w ? 1:0;
        }
        return $list;
    }

    /**
     * @param $date
     */
    public function getPoemActivityPlanByDate($clockinActivityId, $date)
    {
        $list = Db::table($this->primaryTable)->alias('a')
            ->leftJoin("yj_lib_poem p", "p.id = a.subject_id")
            ->where('a.clockin_activity_id', '=', $clockinActivityId)
            ->where('a.plan_date', '=', $date)
            ->field("a.*, p.poem_title,p.dynasty,p.poet,p.poem_content,p.annotation,p.translation,p.background,p.appreciation")
            ->select()
            ->toArray();
        return $list;
    }

    /**
     * Desc: 获取打卡活动已经创建计划的日期
     * @param $clockinActivityId
     * Datetime: 2024/11/13 10:35 by zdb
     */
    public function getClockinActivityPlanExistDate($clockinActivityId){
        $list = Db::table($this->primaryTable)->alias('a')
            ->where('a.clockin_activity_id', '=', $clockinActivityId)
            ->where('a.status', '=', 1)
            ->group('a.plan_date')
            ->field('a.plan_date')
            ->select()
            ->toArray();
        $listDate = array_column($list, 'plan_date');
        return $listDate ?: array();
    }

    public function createManyRowOneByOne($arrPlanId, $arrUserId)
    {
        $nowTime = DateUtil::getCurrentDatetime();
        Db::table($this->primaryTable)->startTrans();
        $failData = array();
        foreach($arrPlanId as $planId){
            foreach($arrUserId as $userId){
                $addData = array(
                    'plan_id' => $planId,
                    'user_id' => $userId,
                    'is_clockin' => 1,
                    'status'  => 1,
                    'update_time' => $nowTime
                );
                $res = $this->createRow($addData);
                if($res){
                    $count++;
                }else{
                    $failData[] = $addData;
                }
            }
        }
        $total = count($arrPlanId) * count($arrUserId);
        if($count == $total){
            Db::table($this->primaryTable)->commit();
            return true;
        }else{
            Db::table($this->primaryTable)->rollback();
            return $failData;
        }
    }
}